#include "registerdialog.h"
#include "ui_registerdialog.h"
#include"global.h"
#include"httpmgr.h"
#include<QJsonDocument>
#include<QString>
#include"toast.h"
#include<QTimer>
#include<verificationcodebutton.h>
RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);
    ui->err_tip->setProperty("state","normal");
    repolish(ui->err_tip);


    InitHttpHandler();
    m_connection_timer=new QTimer(this);
    m_countdown=5;

    setupConnections();
}

void RegisterDialog::setupConnections()
{
    // 连接文本变化信号
    connect(ui->user_edit, &QLineEdit::textChanged, this, &RegisterDialog::onUserTextChanged);
    connect(ui->psw_edit, &QLineEdit::editingFinished, this, &RegisterDialog::onPasswordTextChanged);
    connect(ui->email_edit, &QLineEdit::editingFinished, this, &RegisterDialog::onEmailTextChanged);
    connect(ui->varify_edit, &QLineEdit::textChanged, this, &RegisterDialog::onVerifyTextChanged);
    connect(ui->repsw_edit, &QLineEdit::editingFinished, this, &RegisterDialog::onRepswTextChanged);
    connect(_HttpMgr::GetInstance().get(),&HttpMgr::sig_reg_http_finish,this,&RegisterDialog::slot_reg_http_finish);
    connect(m_connection_timer,&QTimer::timeout,this,&RegisterDialog::timecountdown);
    connect(this,&RegisterDialog::starttimeout,ui->getcode_btn,&VerificationCodeButton::onButtonClicked);
    ui->varify_edit->setReadOnly(true);

}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}


void RegisterDialog::timecountdown(){
    if(m_countdown<=0){
        m_connection_timer->stop();
        emit switchtoLogin();
        return;
    }
    m_countdown--;
    qDebug()<<m_countdown;
    auto string =QString("注册成功，%1s后返回登陆界面").arg(m_countdown);
    ui->wait_lab->setText(string);
}

void RegisterDialog::onUserTextChanged(const QString& text)
{
    if (validateField("username", text)) {
        m_errorManager.removeError("username");
        ui->user_edit->setStyleSheet("border: 2px solid green;");
    }
}

void RegisterDialog::onPasswordTextChanged()
{   auto text=ui->psw_edit->text();
    if (validateField("password", text)) {
        m_errorManager.removeError("password");
        ui->psw_edit->setStyleSheet("border: 2px solid green;");
    }
}

void RegisterDialog::onEmailTextChanged()
{   auto text=ui->email_edit->text();
    if (validateField("email", text)) {
        m_errorManager.removeError("email");
        ui->email_edit->setStyleSheet("border: 2px solid green;");
    }
}

void RegisterDialog::onVerifyTextChanged(const QString& text)
{
    if (validateField("verify", text)) {
        m_errorManager.removeError("verify");
        ui->varify_edit->setStyleSheet("border: 2px solid green;");
    }
}

void RegisterDialog::onRepswTextChanged(){
    auto text=ui->repsw_edit->text();
    if(validateField("repsw",text)){
        m_errorManager.removeError("repsw");
        ui->repsw_edit->setStyleSheet("border:2px,solid green;");
    }
}

bool RegisterDialog::validateField(const QString& fieldId, const QString& value)
{
    if (fieldId == "username") {
        if (value.isEmpty()) {
            m_errorManager.addError("username", "用户名不能为空");
            ui->user_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        return true;
    }
    else if (fieldId == "password") {
        if (value.length() < 6) {
            m_errorManager.addError("password", "密码至少需要6个字符");
            ui->psw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        if (value.length() > 15) {
            m_errorManager.addError("password", "密码不能超过15个字符");
            ui->psw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
        if (!regExp.match(value).hasMatch()) {
            m_errorManager.addError("password", "密码只能包含字母、数字和!@#$%^&*");
            ui->psw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        return true;
    }
    else if (fieldId == "email") {

            QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
            if (!regex.match(value).hasMatch()) {
                m_errorManager.addError("email", "邮箱地址格式不正确");
                ui->email_edit->setStyleSheet("border: 2px solid red;");
                return false;

        }

        return true;
    }
    else if (fieldId == "verify") {
        if (value.isEmpty()) {
            m_errorManager.addError("verify", "验证码不能为空");
            ui->varify_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        return true;
    }
    else if(fieldId=="repsw"){
        if(value.isEmpty()){
            m_errorManager.addError("repsw","请确认密码");
            ui->repsw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }

        auto text=ui->psw_edit->text();
        if(text!=value){
            m_errorManager.addError("repsw","两次密码密码不一致");
            ui->repsw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }

        return true;
    }

    return true;
}

void RegisterDialog::switchtoWaitpage(){
    m_connection_timer->stop();
    ui->stackedWidget->setCurrentWidget(ui->page_2);
    m_connection_timer->start(1000);
}


void RegisterDialog::on_getcode_btn_clicked()
{


    ui->varify_edit->setReadOnly(false);
    // 先清除所有现有错误
    m_errorManager.clearAllErrors();

    // 验证所有字段
    bool allValid = true;

    if (!validateField("username", ui->user_edit->text())) allValid = false;
    if (!validateField("email", ui->email_edit->text())) allValid = false;
    if (!validateField("password", ui->psw_edit->text())) allValid = false;
    if (!validateField("repsw", ui->repsw_edit->text())) allValid = false;

    //if (!validateField("verify", ui->varify_edit->text())) allValid = false;

    if (allValid) {
        //Toast::success("所有验证通过，正在提交...", this, 2000);
        // 执行提交逻辑
        QJsonObject json;
        json["email"]=ui->email_edit->text();

        _HttpMgr::GetInstance()->PostHttpReq(QUrl("http://localhost:8080/get_varifycode"),json,ID_GET_VARIFY_CODE,MoudleId::REGISTER);
    } else {
        // 错误管理器会自动按顺序显示错误
        qDebug() << "发现" << m_errorManager.errorCount() << "个错误，将按顺序显示";
    }
}

void RegisterDialog::on_confirm_btn_clicked()
{
    // 先清除所有现有错误
    m_errorManager.clearAllErrors();

    // 验证所有字段
    bool allValid = true;

    if (!validateField("username", ui->user_edit->text())) allValid = false;
    if (!validateField("password", ui->psw_edit->text())) allValid = false;
    if (!validateField("repsw", ui->repsw_edit->text())) allValid = false;
    if (!validateField("email", ui->email_edit->text())) allValid = false;
    if (!validateField("verify", ui->varify_edit->text())) allValid = false;

    if (allValid) {
        //Toast::success("所有验证通过，正在提交...", this, 2000);
        // 执行提交逻辑
        QJsonObject json;
        json["email"]=ui->email_edit->text();
        json["username"]=ui->user_edit->text();
        json["password"]=ui->psw_edit->text();
        json["repsw"]=ui->repsw_edit->text();
        json["varify_code"]=ui->varify_edit->text();

        _HttpMgr::GetInstance()->PostHttpReq(QUrl("http://localhost:8080/user_register"),json,ID_REG_USER,MoudleId::REGISTER);
    } else {
        // 错误管理器会自动按顺序显示错误
        qDebug() << "发现" << m_errorManager.errorCount() << "个错误，将按顺序显示";
        return;
    }


}

void RegisterDialog::ShowTip(QString str,bool ok){
    if(ok){
        ui->err_tip->setText(str);
    }
    else{
        ui->err_tip->setText(str);
        ui->err_tip->setProperty("state","err");
    }
    repolish(ui->err_tip);
}
void RegisterDialog::slot_reg_http_finish(ReqId id,QString res,Ecode error){
    if(error!=Ecode::SUCCESS){
       // ShowTip("网络错误",false);
        Toast::error("网络错误",this);
        return;
    }
    emit starttimeout();
    QJsonDocument jdoc=QJsonDocument::fromJson(res.toUtf8());
    if(jdoc.isNull()||!jdoc.isObject()){
       // ShowTip("json解析错误",false);
        Toast::error("json解析错误",this);
        return;
    }
    QJsonObject jobj=jdoc.object();

    m_handler[id](jobj);
    return;
}
void RegisterDialog::InitHttpHandler(){
    m_handler.insert({ID_GET_VARIFY_CODE,
                      std::function<void(QJsonObject&)>([this](QJsonObject &jobj)
                        {
                          int error = jobj["error"].toInt();
                          auto msg=jobj["msg"].toString();
                          if(error != Ecode::SUCCESS){
                              //ShowTip("参数出错", false);
                               Toast::error(msg,this);
                              return;
                          }
                          auto email = jobj["email"].toString();
                          //ShowTip("验证码已经发送，请查收", true);
                          Toast::info("验证码已经发送，请查收",this);
                          qDebug()<<email;
                      })});
    m_handler.insert({ID_REG_USER,std::function<void(QJsonObject&)>([this](QJsonObject &jobj){

                          int error = jobj["error"].toInt();
                          auto msg=jobj["msg"].toString();
                          if(error != Ecode::SUCCESS){
                              //ShowTip("参数出错", false);
                              Toast::error(msg,this);
                              return;
                          }
                          auto email = jobj["email"].toString();
                          //ShowTip("验证码已经发送，请查收", true);
                          //Toast::info("注册成功",this);
                          switchtoWaitpage();
                      })});

}
HttpMgr::~HttpMgr(){

}




void RegisterDialog::on_return_btn_clicked()
{
    m_connection_timer->start();
    emit switchtoLogin();
}


void RegisterDialog::on_cancel_btn_clicked()
{
    m_connection_timer->stop();
    emit switchtoLogin();
}

